<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <title>百宝箱管理 - 后台管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/admin.css">
    <!-- 移除错误的 Sortable CSS 引用，Sortable仅提供JS，无需CSS文件 -->
    
    <style>
        body {
            background-color: #0d1117;
            color: #e6edf3;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

            position: relative;
        }

        /* 背景图片样式，与首页保持一致 */
        .bg-image {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            opacity: 0.9;
            transition: opacity 0.5s ease;
        }

        .container-fluid {
            max-width: 1400px;
        }

        /* 页面标题区域 */
        .page-header {
            background: linear-gradient(135deg, rgba(102, 178, 255, 0.1), rgba(102, 178, 255, 0.05));
            border-radius: 15px;
            border: 1px solid rgba(102, 178, 255, 0.2);
            padding: 30px;
            margin-bottom: 30px;
        }

        .page-header h1 {
            color: #66b2ff;
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .page-header .subtitle {
            color: #8b949e;
            margin-bottom: 20px;
        }

        .stats-cards {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .stats-card {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(102, 178, 255, 0.1);
            border-radius: 12px;
            padding: 15px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .stats-card i {
            font-size: 24px;
            color: #66b2ff;
        }

        .stats-card .value {
            font-size: 16px;
            color: #e6edf3;
            font-weight: bold;
        }

        .stats-card .label {
            font-size: 12px;
            color: #8b949e;
        }

        /* 按钮样式 */
        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .btn-outline-primary {
            border-color: #66b2ff;
            color: #66b2ff;
        }

        .btn-outline-primary:hover {
            background: rgba(102, 178, 255, 0.2);
            border-color: #66b2ff;
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            border: none;
            color: #000;
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #1e7e34);
            border: none;
        }

        /* 搜索和筛选 */
        .search-filter-section {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(102, 178, 255, 0.1);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .search-input {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(102, 178, 255, 0.3);
            border-radius: 8px;
            color: #e6edf3;
            padding: 10px 15px;
        }

        .search-input:focus {
            background: rgba(255, 255, 255, 0.08);
            border-color: #66b2ff;
            box-shadow: 0 0 0 3px rgba(102, 178, 255, 0.1);
            color: #e6edf3;
        }

        .search-input::placeholder {
            color: #8b949e;
        }

        .form-select {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(102, 178, 255, 0.3);
            color: #e6edf3;
        }

        .form-select:focus {
            background: rgba(255, 255, 255, 0.08);
            border-color: #66b2ff;
            box-shadow: 0 0 0 3px rgba(102, 178, 255, 0.1);
            color: #e6edf3;
        }

        /* 卡片网格 */
        .treasure-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 20px;
        }

        .treasure-card {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(102, 178, 255, 0.1);
            border-radius: 12px;
            padding: 16px;
            display: flex;
            align-items: center;
            gap: 16px;
            cursor: grab;
        }

        .treasure-card:active { cursor: grabbing; }

        .icon-cell {
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            background: rgba(102, 178, 255, 0.08);
            border: 1px solid rgba(102, 178, 255, 0.2);
        }

        .treasure-icon {
            font-size: 28px;
            color: #66b2ff;
            display: inline-block;
            width: 28px;
            height: 28px;
        }

        /* 图片图标样式 */
        .treasure-icon-img {
            width: 28px;
            height: 28px;
            object-fit: cover;
            border-radius: 6px;
            border: 1px solid rgba(102, 178, 255, 0.3);
            background-color: rgba(255, 255, 255, 0.05);
        }

        .treasure-title { color: #e6edf3; font-weight: 600; }
        .treasure-desc { color: #8b949e; }

        /* 拖拽状态样式（由 SortableJS JS 控制，无需CSS文件） */
        .sortable-ghost { opacity: 0.5; }
        .sortable-chosen { outline: 1px dashed rgba(102, 178, 255, 0.5); }
    </style>

    <!-- 页面主体见 body -->
</head>
<body class="admin-theme">
<div class="bg-image" th:if="${backgroundImage != null and !backgroundImage.isEmpty()}" th:style="|background-image: url(${backgroundImage});|"></div>
<div th:replace="~{fragments/navbar :: navbar}"></div>
<div class="container-fluid">
    <div class="page-header mb-4">
        <h1>百宝箱管理</h1>
        <p class="subtitle">在这里添加网站收藏或上传文件</p>
        <div class="action-bar mt-2">
            <div class="btn-group gap-2">
                <a href="/" class="btn btn-outline-primary" title="返回前台主页" data-bs-toggle="tooltip"><i class="bi bi-house"></i> 返回首页</a>
                <a href="/treasure" class="btn btn-outline-primary" title="查看前台百宝箱" data-bs-toggle="tooltip"><i class="bi bi-gift"></i> 返回百宝箱</a>
            </div>
        </div>
    </div>

    <!-- 添加网站与文件表单（改为标签切换） -->
    <div class="search-filter-section mb-4">
        <ul class="nav nav-pills mb-3" id="formTabs">
            <li class="nav-item"><button type="button" class="nav-link active" data-target="#websiteFormSection" title="保存外部链接资源" data-bs-toggle="tooltip">新建网站收藏</button></li>
            <li class="nav-item"><button type="button" class="nav-link" data-target="#fileFormSection" title="上传图片或PDF等可预览文件" data-bs-toggle="tooltip">上传文件</button></li>
        </ul>

        <div id="websiteFormSection">
            <form id="addWebsiteForm" enctype="multipart/form-data" class="mb-4">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">显示名称</label>
                        <input type="text" name="displayName" class="form-control search-input" placeholder="例如：GitHub" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">网站地址</label>
                        <input type="url" name="url" class="form-control search-input" placeholder="https://example.com" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">图标文件（可选）</label>
                        <input type="file" name="iconFile" accept="image/*" class="form-control">
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">描述（可选）</label>
                        <input type="text" name="description" class="form-control search-input" placeholder="一句话介绍该网站">
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="submit" class="btn btn-success w-100"><i class="bi bi-bookmark-plus"></i> 添加网站收藏</button>
                    </div>
                </div>
            </form>
            <div id="addWebsiteMessage" class="mt-3"></div>
        </div>

        <div id="fileFormSection" class="d-none">
            <form id="uploadFileForm" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">选择文件</label>
                        <input type="file" name="file" class="form-control" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">显示名称（可选）</label>
                        <input type="text" name="displayName" class="form-control search-input" placeholder="例如：项目文档">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">描述（可选）</label>
                        <input type="text" name="description" class="form-control search-input" placeholder="一句话介绍该文件">
                    </div>
                    <div class="col-12 d-flex justify-content-end">
                        <button type="submit" class="btn btn-warning"><i class="bi bi-upload"></i> 上传文件</button>
                    </div>
                </div>
            </form>
            <div id="uploadFileMessage" class="mt-3"></div>
        </div>
    </div>

    <!-- 项目列表 -->
    <div class="treasure-grid" id="treasureGrid" th:if="${allItems != null}">
        <div class="treasure-card" th:each="item : ${allItems}" th:data-id="${item.id}">
            <div class="icon-cell">
                <span th:if="${item.icon == null or #strings.isEmpty(item.icon)}">
                    <i class="treasure-icon bi bi-globe"></i>
                </span>
                <span th:if="${item.icon != null and (item.icon.startsWith('http') or item.icon.startsWith('/'))}" th:remove="tag">
                    <img th:src="${item.icon}" alt="icon" class="treasure-icon-img">
                </span>
                <span th:if="${item.icon != null and !(item.icon.startsWith('http') or item.icon.startsWith('/'))}" th:remove="tag">
                    <i class="treasure-icon" th:classappend="' ' + ${item.icon}"></i>
                </span>
            </div>
            <div class="flex-grow-1">
                <div class="treasure-title" th:text="${item.displayName}">名称</div>
                <div class="treasure-desc" th:text="${item.description}">描述</div>
            </div>
            <div class="d-flex align-items-center gap-2">
                <a class="btn btn-outline-primary btn-sm" th:href="${item.url}" th:if="${item.type.name() == 'WEBSITE'}" target="_blank" title="在新窗口打开" data-bs-toggle="tooltip"><i class="bi bi-box-arrow-up-right"></i></a>
                <button class="btn btn-outline-primary btn-sm no-drag" th:if="${item.type.name() == 'FILE'}" th:attr="data-id=${item.id},data-file=${item.filePath},data-name=${item.originalFileName},data-mime=${item.mimeType}" onclick="adminPreview(this)" title="在新窗口打开预览" data-bs-toggle="tooltip"><i class="bi bi-eye"></i></button>
                <button class="btn btn-warning btn-sm" th:attr="data-id=${item.id}" onclick="toggleItem(this)" title="启用/停用" data-bs-toggle="tooltip"><i class="bi" th:classappend="${item.enabled} ? 'bi-toggle-on' : 'bi-toggle-off'"></i></button>
                <button class="btn btn-danger btn-sm" th:attr="data-id=${item.id}" onclick="deleteItem(this)" title="删除该条目" data-bs-toggle="tooltip"><i class="bi bi-trash"></i></button>
            </div>
        </div>
    </div>
</div>

<!-- 文件预览模态框 -->
<div class="modal fade" id="filePreviewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content bg-dark text-light border-0 rounded-0">
      <div class="modal-header border-0 p-2">
        <h5 class="modal-title" id="filePreviewTitle">文件预览</h5>
        <div class="d-flex align-items-center gap-2 ms-auto">
          <a id="fileDownloadBtn" class="btn btn-sm btn-primary" href="#" target="_blank" download><i class="bi bi-download me-1"></i>下载</a>
          <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">关闭</button>
        </div>
      </div>
      <div class="modal-body p-0" style="height:100vh">
          <iframe id="filePreviewFrame" style="width:100%; height:100vh; border:0;" frameborder="0"></iframe>
          <div id="filePreviewUnsupported" class="text-center text-muted" style="display:none; padding:20px;">
              此类型暂不支持在线预览，请点击下载。
          </div>
      </div>
    </div>
  </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- SortableJS -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<script>
    // 全局变量
    let sortable = null;
    let selectMode = false;
    let selectedItems = new Set();
    let originalOrder = [];

    document.addEventListener('DOMContentLoaded', function() {
        initializePage();
        initializeSortable();
        initializeEventListeners();
        bindFormTabs();
        checkEmptyState();

        const previewModalEl = document.getElementById('filePreviewModal');
        if (previewModalEl) {
            previewModalEl.addEventListener('hidden.bs.modal', function(){
                const frame = document.getElementById('filePreviewFrame');
                if (frame) frame.src = '';
            });
        }
    });

    function initializePage() {
        const items = document.querySelectorAll('.treasure-card');
        originalOrder = Array.from(items).map(item => item.dataset.id);
    }

    function initializeSortable() {
        const grid = document.getElementById('treasureGrid');
        sortable = Sortable.create(grid, {
            animation: 150,
            ghostClass: 'sortable-ghost',
            chosenClass: 'sortable-chosen',
            handle: '.icon-cell',
            onEnd: function(evt) {
                const newOrder = Array.from(grid.children).map(item => item.dataset.id);
                if (JSON.stringify(newOrder) !== JSON.stringify(originalOrder)) {
                    document.getElementById('saveOrder')?.style && (document.getElementById('saveOrder').style.display = 'inline-block');
                }
            }
        });
    }

    function initializeEventListeners() {
        // ... existing code ...
    }

    function bindFormTabs(){
      const tabs = document.querySelectorAll('#formTabs .nav-link');
      const websiteSec = document.getElementById('websiteFormSection');
      const fileSec = document.getElementById('fileFormSection');
      tabs.forEach(tab => {
        tab.addEventListener('click', function(){
          tabs.forEach(t => t.classList.remove('active'));
          this.classList.add('active');
          const target = this.dataset.target;
          websiteSec.classList.toggle('d-none', target !== '#websiteFormSection');
          fileSec.classList.toggle('d-none', target !== '#fileFormSection');
        });
      });
    }

    // CSRF Token
    const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content');

    // 提交添加网站表单
    const addForm = document.getElementById('addWebsiteForm');
    if (addForm) {
      addForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(addForm);
        const headers = csrfHeader ? { [csrfHeader]: csrfToken } : {};
        const res = await fetch('/admin/treasure/website', { method: 'POST', body: formData, headers });
        const msgEl = document.getElementById('addWebsiteMessage');
        try {
          const json = await res.json();
          msgEl.className = json.success ? 'alert alert-success' : 'alert alert-danger';
          msgEl.textContent = json.message || (json.success ? '添加成功' : '添加失败');
          if (json.success) { setTimeout(() => location.reload(), 800); }
        } catch (err) {
          msgEl.className = 'alert alert-danger';
          msgEl.textContent = '请求失败';
        }
      });
    }

    // 提交上传文件表单
    const fileForm = document.getElementById('uploadFileForm');
    if (fileForm) {
      fileForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(fileForm);
        const headers = csrfHeader ? { [csrfHeader]: csrfToken } : {};
        const res = await fetch('/admin/treasure/file', { method: 'POST', body: formData, headers });
        const msgEl = document.getElementById('uploadFileMessage');
        try {
          const json = await res.json();
          msgEl.className = json.success ? 'alert alert-success' : 'alert alert-danger';
          msgEl.textContent = json.message || (json.success ? '上传成功' : '上传失败');
          if (json.success) { setTimeout(() => location.reload(), 800); }
        } catch (err) {
          msgEl.className = 'alert alert-danger';
          msgEl.textContent = '请求失败';
        }
      });
    }

    async function toggleItem(btn){
      const id = btn.getAttribute('data-id');
      const headers = csrfHeader ? { [csrfHeader]: csrfToken } : {};
      const res = await fetch(`/admin/treasure/toggle/${id}`, { method: 'POST', headers });
      const data = await res.json();
      if (data.success) { location.reload(); }
    }

    async function deleteItem(btn){
      const id = btn.getAttribute('data-id');
      if (!confirm('确定删除该项目吗？')) return;
      const headers = csrfHeader ? { [csrfHeader]: csrfToken } : {};
      const res = await fetch(`/admin/treasure/delete/${id}`, { method: 'DELETE', headers });
      const data = await res.json();
      if (data.success) { location.reload(); }
    }

    function adminPreview(btn){
      const file = btn.getAttribute('data-file');
      const name = btn.getAttribute('data-name');
      const mime = btn.getAttribute('data-mime');
      const id = btn.getAttribute('data-id');
      previewFileById(id, file, name, mime);
    }

    // 文件预览：改为在新窗口中打开
    function previewFileById(id, filePath, fileName, mime){
      if (!id) return;
      const ext = (fileName || '').split('.').pop().toLowerCase();
      const isImage = (mime && mime.startsWith('image/')) || ['jpg','jpeg','png','gif','bmp','webp','svg'].includes(ext);
      const isPdf = (mime && mime.toLowerCase().includes('pdf')) || ext === 'pdf';
      const previewUrl = '/treasure/preview/' + id;
      const downloadUrl = '/treasure/download/' + id;

      if (isImage || isPdf) {
        window.open(previewUrl, '_blank');
      } else {
        window.open(downloadUrl, '_blank');
      }
    }
</script>
</body>
</html>